<template>
  <div class="flex gap-x-3">
    <div @click="selectProvince" class="border rounded border-black flex-1 p-1">
      {{ province || '请选择省份' }}
    </div>
    <div @click="selectCity" class="border rounded border-black flex-1 p-1">
      {{ city || '请选择城市' }}
    </div>
  </div>
  <div class="text-sm text-gray-700">注：请如实选择收款账号常用地，减少风控。</div>
  <van-popup teleport="body" v-model:show="show" position="bottom">
    <van-picker
      title="请选择"
      :columns="columns"
      :columns-field-names="{ text: 'name', value: 'id' }"
      @confirm="selectConfirm"
      @cancel="show = false"
    ></van-picker>
  </van-popup>
</template>
<script setup lang="ts">
import { GetAreaApi } from '@/apis/collection'
import { onMounted, ref, watch, defineEmits } from 'vue'

const columns = ref([])
const show = ref(false)
const province = ref('')
const city = ref('')
let type = 1
const formRef = ref({
  province: '',
  city: ''
})
const emit = defineEmits(['change'])

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }
})

watch(
  () => props.data.city,
  async () => {
    await loadCityData('')
    if (props.data.province || props.data.city) {
      formRef.value.city = props.data.city
      formRef.value.province = props.data.province
      await initCity()
    }
  }
)

onMounted(async () => {
  await loadCityData('')
  if (props.data.province || props.data.city) {
    formRef.value.city = props.data.city
    formRef.value.province = props.data.province
    await initCity()
  }
})

const initCity = async () => {
  for (let index = 0; index < columns.value.length; index++) {
    const element = columns.value[index]
    if (element.id == props.data.province) {
      province.value = element.name
    }
  }
  await loadCityData(props.data.province)
  for (let index = 0; index < columns.value.length; index++) {
    const element = columns.value[index]
    if (element.id == props.data.city) {
      city.value = element.name
    }
  }
}

const loadCityData = async (e) => {
  await GetAreaApi({ id: e }).then((res) => {
    columns.value = res.list
  })
  return true
}

const selectProvince = () => {
  loadCityData('')
  type = 1
  city.value = ''
  formRef.value.city = ''
  show.value = true
}

const selectCity = () => {
  loadCityData(formRef.value.province)
  type = 2
  show.value = true
}

const selectConfirm = ({ selectedValues, selectedOptions }) => {
  if (type === 1) {
    province.value = selectedOptions[0].name
    formRef.value.province = selectedValues[0]
  } else if (type === 2) {
    city.value = selectedOptions[0].name
    formRef.value.city = selectedValues[0]
  }
  show.value = false
}

watch(
  () => formRef.value.city,
  (val) => {
    if (!val) return
    emit('change', formRef.value)
  }
)
</script>
